package com.smedi.ismedi.database.starter.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.smedi.ismedi.database.starter.property.TenantLineInnerProperty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class MyBatisPlusConfig {
    private final TenantLineInnerProperty tenantLineInnerProperty;

    /**
     * 多租户
     *
     * @param interceptor
     */
    private void assembleTenant(MybatisPlusInterceptor interceptor) {
        boolean used = false;
        if (tenantLineInnerProperty.getClassPackages() != null) {
            for (String pkg : tenantLineInnerProperty.getClassPackages()) {
                try {
                    Class handler = Class.forName(pkg);

                    // 设置挂钩
                    TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor();
                    tenantLineInnerInterceptor.setTenantLineHandler((TenantLineHandler) handler.newInstance());
                    interceptor.addInnerInterceptor(tenantLineInnerInterceptor);

                    log.info("+ handler: {}", pkg);
                    used = true;
                } catch (ClassNotFoundException e) {
                    log.info("- ClassNotFoundException: {}", pkg);
                } catch (InstantiationException e) {
                    log.info("- InstantiationException: {}", pkg);
                } catch (IllegalAccessException e) {
                    log.info("- IllegalAccessException: {}", pkg);
                }
            }
        }

        if (!used) {
            log.info("未添加多租户");
        } else {
            log.info("添加多租户");
        }
    }

    @Bean
    public MybatisPlusInterceptor initializeInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        log.info("添加乐观锁");

        // 多租户
        assembleTenant(interceptor);

        // 分页
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        log.info("添加分页插件");

        return interceptor;
    }
}
